package com.lungle.warmdiary.app.view.me.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.MediaAccount;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.model.response.WechatExist;
import com.lungle.warmdiary.app.ui.dialog.WaitDialog;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MediaAddFragment extends BaseFragment {
    private static final String MEDIA_ADD_SCREEN = "media_add_screen";

    @Bind(R.id.iv_wechat_add)
    ImageView mIvWechatAdd;


    private UMShareAPI mShareAPI = null;
    private Timer mTimer;
    private WaitDialog mDialog;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_media_add, container, false);
        initView(view);
        initData();
        mShareAPI = UMShareAPI.get(getActivity());
        return view;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void initView(View view) {
        ButterKnife.bind(this, view);
    }

    @Override
    public void initData() {


    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(MEDIA_ADD_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(MEDIA_ADD_SCREEN);
        MobclickAgent.onPause(getActivity());

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @OnClick({R.id.iv_wechat_add})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.iv_wechat_add:
                if (mDialog == null){
                    mDialog = showWaitDialog("正在绑定...");
                    mDialog.show();
                }else{
                    mDialog.setMessage("正在绑定...");
                    mDialog.show();
                }
                monitor();
                getLoginAuth();
                break;

        }


    }

    private void monitor() {
        if (mTimer != null) mTimer.cancel();
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mDialog != null) {
                    mDialog.dismiss();
                }
            }
        }, 0, 39 * 1000);
    }

    private void showMessage(String message) {
        if (mDialog != null) {
            mDialog.setMessage(message);
        }
    }

    private void hideMessage() {
        if (mDialog != null) {
            mDialog.hide();

        }

    }

    private void getLoginAuth() {
        mShareAPI.doOauthVerify(getActivity(), SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                if (data != null) {
                    showMessage("正在验证...");
                    checkWechat(data.get("unionid"));
                } else {
                    hideMessage();
                }


            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                hideMessage();
                AppContext.showToast("绑定失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                hideMessage();
                AppContext.showToast("取消绑定");
            }

        });
    }


    private void checkWechat(String unionid) {
        ApiFactory.getUserApi().validateWid(unionid).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<WechatExist>>(getActivity()) {
                    @Override
                    public void onNext(Result<WechatExist> wechatExistResult) {
                        WechatExist data = wechatExistResult.getData();
                        if (data.isExist()) {
                            AppContext.showToast("帐号已被注册");
                           hideMessage();
                        } else {
                            showMessage("获取信息...");
                            getWechatInfo();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideMessage();
                        AppContext.showToast("请稍候再试");
                    }
                });
    }

    private void getWechatInfo() {
        mShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
                hideMessage();
                if (data != null) {
                    if (data.get("profile_image_url") == null) {
                        AppContext.showToast("缺少头像,无法添加");
                        return;

                    }
                    MediaAccount mediaAccount = new MediaAccount();
                    mediaAccount.setUnionid(data.get("unionid"));
                    //1:男;0: 女
                    String gender = data.get("gender");
                    if (gender.equals("0")) {
                        mediaAccount.setGender(User.CODE_FAMALE);
                    } else {
                        mediaAccount.setGender(User.CODE_MALE);
                    }
                    mediaAccount.setGender(Integer.valueOf(data.get("gender")));
                    mediaAccount.setLogo(data.get("profile_image_url"));
                    mediaAccount.setOpenid(data.get("openid"));
                    mediaAccount.setName(data.get("screen_name"));
                    UIHelper.showMediaAddResult(getActivity(), mediaAccount, MediaAddResultFragment.ACTION_CREATE);
                    getActivity().finish();
                }


            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                hideMessage();
                AppContext.showToast("绑定失败,请重试");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                hideMessage();
                AppContext.showToast("操作取消");
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDialog != null)
            mDialog.dismiss();
    }
}
